package com.unibeta.cloudtest.mesher.modules.schedule.service.impl;

import java.util.Date;

import com.unibeta.cloudtest.CloudTestOutput;
import com.unibeta.cloudtest.mesher.config.CloudTestBootStrap;
import com.unibeta.cloudtest.mesher.config.ConfigurationProxy;
import com.unibeta.cloudtest.mesher.modules.schedule.entity.Job;
import com.unibeta.cloudtest.mesher.modules.schedule.entity.JobRunHistory;
import com.unibeta.cloudtest.mesher.modules.schedule.repo.JobRepo;
import com.unibeta.cloudtest.mesher.modules.schedule.repo.JobRunHistoryRepo;
import com.unibeta.cloudtest.tool.CloudTestReportor;
import com.unibeta.cloudtest.util.CloudTestUtils;
import com.unibeta.cloudtest.util.ObjectDigester;

import cn.hutool.cron.task.Task;

public class ScheduleJobTask implements Task {

	private Job job;

	public ScheduleJobTask(Job job) {
		this.job = job;
	}

	private ScheduleJobTask() {
	}

	@Override
	public void execute() {
		JobRepo jobRepo = CloudTestBootStrap.getApplicationContext().getBean(JobRepo.class);
		JobRunHistoryRepo jobRunHistoryRepo = CloudTestBootStrap.getApplicationContext()
				.getBean(JobRunHistoryRepo.class);

		Job j = jobRepo.getOne(job.getId());

		JobRunHistory jobRun = new JobRunHistory();
		jobRun.setJobId(job.getId());
		jobRun.setStartTime(new Date());

		CloudTestOutput result = null;
		String message = null;
		try {
			ConfigurationProxy.setCLOUDTEST_HOME(job.getHome());
			result = new CloudTestReportor().report(job.getName(), job.getTasks(), job.getMails(), job.getName());
			message = ObjectDigester.toXML(result);
			j.setMessage(message);
			jobRepo.save(j);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

			message = CloudTestUtils.printExceptionStackTrace(e);

		} finally {
			j.setMessage(message);
			jobRepo.save(j);

			jobRun.setFinishTime(new Date());
			jobRun.setMessage(message);
			jobRunHistoryRepo.save(jobRun);
		}

	}

}
